const db = require('../utils/db');

module.exports = {
    /**
     * 添加预购记录
     */
    async addOrder(formData) {
        let res = await db.insert('order_record', formData);
        return res;
    },
    /**
     * 获取预购记录
     */
    async getOrder(formData) {
        let sql = `
        SELECT book_id FROM order_record
        WHERE buyer_id = '${formData.user}'
        and book_id IN (SELECT book_id from book_info WHERE state != '已售')
       `;
        let res = await db.query(sql);
        return res;
    },
    /**
     * 修改预购记录
     */
    async modifyOrder(formData) {
        let sql = `
        UPDATE order_record set state=REPLACE(state,0,1)
        WHERE book_id = '${formData.book_id}'
        and buyer_id = '${formData.buyer}'
        `;
        let result = await db.query(sql);
        return result;
    },
    /**
     * 获取预购人员
     */
    async getOrderPeople(formData) {
        let sql = `
        SELECT buyer_id FROM order_record
        WHERE book_id = '${formData.book_id}'
       `;
        let res = await db.query(sql);
        return res;
    },
    /**
     * 获取交易对象
     */
    async getTradePeople(formData) {
        let sql = `
        SELECT buyer_id FROM order_record
        WHERE book_id = '${formData.book_id}'
        and state = 1 limit 1
       `;
        let res = await db.query(sql);
        if (Array.isArray(res) && res.length > 0) {
            res = res[0];
        } else {
            res = null;
        }
        return res;
    },
    /**
     * 获取在售记录
     */
    async getForSale(formData) {
        let sql = `
        SELECT book_id FROM book_info
        WHERE user_id = '${formData.user_id}'
        and state != '已售'
       `;
        let res = await db.query(sql);
        return res;
    }
}